<script setup>
import ChatUserList from '@/components/app-chat/cpn/chat-user-list/chat-user-list.vue'
import ChatDetail from '@/components/app-chat/cpn/chat-detail/chat-detail.vue'
import useChatStore from '@/store/chat'
import {storeToRefs} from 'pinia'
import {onUnmounted, ref} from 'vue'

//聊天内容
const chatStore = useChatStore()
const {chatUserListMap, isLoaded, chatContent, activeChatId, isContentLoaded} = storeToRefs(chatStore)

chatStore.fetchChatListAction()

//开启轮询
const detailRef = ref(null)
let timer = ref(0)
timer.value = setInterval(() => {
  chatStore.fetchChatListAction().then((isChange) => {
    //如果有发生变化则移动到最底部
    isChange && detailRef.value?.handleScrollToBottom()
  })
}, 2000)

//点击用户
const handleSelect = (id) => {
  if (activeChatId.value === id) return
  activeChatId.value = id
}

onUnmounted(() => {
  chatStore.resetStateAction()
  timer.value && clearInterval(timer.value)
})
</script>

<template>
  <div class="app-chat" v-loading="!isLoaded">
    <template v-if="isLoaded">
      <chat-user-list :chat-user-list-map="chatUserListMap" :active-chat-id="activeChatId" @select="handleSelect"/>
      <div class="content-box" v-loading="!isContentLoaded">
        <template v-if="isContentLoaded">
          <chat-detail ref="detailRef" :chat-content="chatContent"/>
        </template>
      </div>
    </template>
  </div>
</template>

<style lang="scss" scoped>
.app-chat {
  @include flex-box;
  gap: $spacing-2;
  height: 600px;
}

.content-box {
  @include full-box;
}
</style>
